<template>
  <p>管理学生</p>
  <div>
    <div class="search-form">
      <el-form :model="searchForm" :rules="rules" inline>
        <el-form-item label="学生ID">
          <el-input v-model="searchForm.studentId" @keyup.enter="search" placeholder="请输入学生ID"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名">
          <el-input v-model="searchForm.studentName" @keyup.enter="search" placeholder="请输入学生姓名"></el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 40px">
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="inputDiv">
      <el-form-item label="姓名">
        <el-input v-model="addForm.name" />
      </el-form-item>
      <el-form-item label="账号">
        <el-input v-model="addForm.studentID" />
      </el-form-item>
      <div style="display: flex;flex-direction: row;">
        <el-upload v-model:file-list="fileList" class="upload-demo" action="http://8.130.42.115:8000/teacher/upload"
          :on-preview="handlePreview" :on-exceed="handleExceed">
          <!--                <div type="primary">批量导入</div>-->
          <el-button class="import-el-button" style="margin-left: 245px">批量导入</el-button>
        </el-upload>
        <el-button class="import-el-button" @click="addPerson()" style="margin-left: 15px">手动导入</el-button>
      </div>
      <br>
    </div>
    <div style="margin-left: 303px; margin-bottom: 6px;display: flex;flex-direction: row">
      <el-button class="import-el-button" @click="downLoadStu()" style="margin-bottom: 3px">下载名单</el-button>
      <el-button class="import-el-button" @click="deleteBatchTeacher">批量删除</el-button>
    </div>
    <el-table ref="multipleTableRef" :data="displayedPeople" style="width: 100%;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column fixed label="操作" width="360">
        <template #default="{ row }">
          <el-button v-if="matchUrlData === 'stu'" link type="primary" size="small" @click="editPerson(row)">编辑</el-button>
          <el-dialog title="编辑学生信息" v-model="dialogFormVisible" :before-close="handleClose">
            <el-form :model="form">
              <el-form-item label="学生姓名" :label-width="formLabelWidth">
                <el-input v-model="form.name" autocomplete="off" />
              </el-form-item>
              <el-form-item label="学生ID" :label-width="formLabelWidth">
                <el-input v-model="form.studentID" autocomplete="off" />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer" @click="dialogFormVisible = false">
                <el-button>取消</el-button>
                <el-button type="primary" @click="saveEdit(row)">
                  确定
                </el-button>
              </span>
            </template>
          </el-dialog>
          <el-button link type="primary" size="small" @click="deleteSingleStudentFun(row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column property="name" label="学生姓名" />
      <el-table-column property="studentID" label="学生ID" show-overflow-tooltip />
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[5, 10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="people.length">
        </el-pagination>
    <div style="margin-top: 20px">
      <!--      <el-button @click="deleteBatchTeacher">批量删除</el-button>-->
    </div>
  </div>
</template>

<script setup>
import { ref, toRefs, reactive, onMounted, watch } from 'vue';
import { ElNotification, ElDialog, ElForm, ElFormItem, ElInput, ElButton,ElPagination } from 'element-plus';
import XLSX from 'xlsx';
import { useStore } from '../../Admin/store'
import { useStudentListStore } from '@/stores/studentList.js'
import { ElTable, ElUpload } from 'element-plus'
import { useClassIDStore } from '@/stores/classID.js'
import { addSingleStudent, deleteSingleStudent, editorStudentInfo, deleteBatchStudents, selectSudentInfoService, allCourseStudentAttend, deleteSingleStudentInClass, deleteBatchStudentsInClass } from '@/api/adminApi/allAdmin'
import { useRoute } from 'vue-router';
const router = useRoute();
const classIDstore = useClassIDStore();
const studentistStore = useStudentListStore()
const store = useStore()
const fileList = ref()
const searchForm = ref({
    studentId: '',
    studentName: ''
});
const currentPage = ref(1);
const pageSize = ref(10);
const displayedPeople = ref([]); // 当前显示的数据
const resetForm = () => {
    searchForm.value.studentId = '';
    searchForm.value.studentName = '';
};
const paginateData = () => {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    return people.value.slice(startIndex, endIndex);
};
const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    displayedPeople.value = paginateData();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    displayedPeople.value = paginateData();
}
onMounted(() => {
    displayedPeople.value = paginateData();
})
watch(
  () => studentistStore.studentList,
  () => people.value = studentistStore.studentList,
  { deep: true }
)
const props = defineProps({
  tableData: Array
})
const people = ref(studentistStore.studentList);
const form = ref({
  studentID: '',
  name: '',
  editIndex: 0
});
const addForm = ref({
  name: '',
  studentID: ''
});
const multipleTableRef = ref()
const dialogFormVisible = ref(false);
const addPerson = async () => {
  const data = {
    name: addForm.value.name,
    studentID: addForm.value.studentID,
    password: '1234',
    classID: classIDstore.classID
  };
  people.value.push(data)
  addForm.value = {}
  await addSingleStudent(data)
};

//保存多选行的信息
const selectionRow = ref([])
const handleSelectionChange = (section) => {
  selectionRow.value = section
  console.log(selectionRow.value, 'selectionRow')
}
//批量删除
const deleteBatchTeacher = async () => {
  const data = []
  selectionRow.value.map((item, index) => {
    data.push(item.studentID)
    people.value.map((list, idx) => {
      if (item.studentID === list.studentID)
        people.value.splice(idx, 1)
    })
  })
  await deleteBatchStudents(data)
}
const editPerson = async (row) => {
  // 处理选中行数据
  form.value.name = row.name;
  form.value.studentID = row.studentID;
  dialogFormVisible.value = true;
}
//删除单个學生
const deleteSingleStudentFun = async (row) => {
  const index = people.value.findIndex(item => item.studentID === row.studentID);
  people.value.splice(index, 1)
  const data = {
    classID: store.detailClass.classID,
    studentID: row.studentID
  }
  await deleteSingleStudentInClass(data)
};
//保存编辑内容
const saveEdit = async () => {
  const data = {
    name: form.value.name,
    password: "123456",//设为初始值
    studentID: form.value.studentID
  }
  await editorStudentInfo(data)
  const index = people.value.findIndex((item) => item.studentID === form.value.studentID)
  people.value[index].name = form.value.name
}
const searchQuery = ref('');

const search = async () => {
    let result={
        studentID:searchForm.value.studentId,
        name:searchForm.value.studentName,
        pageSize:20,
        pageNum:1
    }
    const res = await selectSudentInfoService(result)
    displayedPeople.value = res.data
    people.value=res.data

};

// 将响应式数据转换为可解构的对象
const { value: reactivePeople } = toRefs(people);
const downLoadStu = () => {
  const worksheet = XLSX.utils.json_to_sheet(people.value);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  XLSX.writeFile(workbook, 'students.xlsx');
}
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

    // 将数据存入ref
    people.value = jsonData.map((row, index) => {
      if (index === 0) return null; // 跳过表头行
      const [id, studentID, studentName] = row;
      return { id, studentID, studentName };
    }).filter(Boolean);
  };

  reader.readAsArrayBuffer(file);
}

</script>

<style>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.import_div {
  display: inline-block;
  margin-left: 28%;
}
</style>


<!-- 引入 Element Plus 组件库 -->
<script>
export default {
  components: {
    ElNotification,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
  },
};
</script>@/api/adminApi/allAdmin
<!-- <template>
    <p>管理學生</p>
    <div>
        <el-form-item class="search-form">
            <el-input type="text" v-model="searchQuery" placeholder="输入关键词进行搜索,关键词间用&隔开，第一个部分为id，第二个部分为name" />
            <el-button @click="search">搜索</el-button>
        </el-form-item>
        <div class="inputDiv">
            <el-form-item label="姓名">
                <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="账号">
                <el-input v-model="addForm.studentID" />
            </el-form-item>
            <el-button class="import-el-button" @click="addPerson()">手动导入</el-button>
        </div>
        <div class="import_div">
            <el-upload v-model:file-list="fileList" class="upload-demo" action="http://8.130.42.115:8000/teacher/upload"
                :on-preview="handlePreview" :on-exceed="handleExceed">
                <div type="primary">批量导入</div>
            </el-upload>
        </div>
        <el-button class="import-el-button" @click="downLoadStu()">下载名单</el-button>
        <el-table ref="multipleTableRef" :data="people" style="width: 100%;height: 30vh" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column fixed label="操作" width="360">
                <template #default="{ row }">
                    <el-button v-if="matchUrlData==='stu'" link type="primary" size="small" @click="editPerson(row)">编辑</el-button>
                    <el-dialog title="编辑学生信息" v-model="dialogFormVisible" :before-close="handleClose">
                        <el-form :model="form">
                            <el-form-item label="学生姓名" :label-width="formLabelWidth">
                                <el-input v-model="form.name" autocomplete="off" />
                            </el-form-item>
                            <el-form-item label="学生ID" :label-width="formLabelWidth">
                                <el-input v-model="form.studentID" autocomplete="off" />
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <span class="dialog-footer" @click="dialogFormVisible = false">
                                <el-button>Cancel</el-button>
                                <el-button type="primary" @click="saveEdit(row)">
                                    Confirm
                                </el-button>
                            </span>
                        </template>
                    </el-dialog>
                    <el-button link type="primary" size="small" @click="deleteSingleStudentFun(row)">删除</el-button>
                </template>
            </el-table-column>
            <el-table-column property="name" label="学生姓名" />
            <el-table-column property="studentID" label="学生ID" show-overflow-tooltip />
        </el-table>
        <div style="margin-top: 20px">
            <el-button @click="deleteBatchTeacher">批量删除</el-button>
        </div>
    </div>
</template>
  
<script setup>
import { ref, toRefs, reactive, computed, watch } from 'vue';
import { ElNotification, ElDialog, ElForm, ElFormItem, ElInput, ElButton } from 'element-plus';
import XLSX from 'xlsx';
import { useStore } from '../../Admin/store'
import {useStudentListStore} from '@/stores/studentList.js'
import { ElTable, ElUpload } from 'element-plus'
import { useClassIDStore } from '@/stores/classID.js'
import { addSingleStudent, deleteSingleStudent, editorStudentInfo, deleteBatchStudents, selectSudentInfoService, allCourseStudentAttend, deleteSingleStudentInClass ,deleteBatchStudentsInClass} from '@/api/adminApi/allAdmin'
import { useRoute } from 'vue-router';
const router = useRoute();
const classIDstore = useClassIDStore();
const studentistStore=useStudentListStore()
const store = useStore()
const fileList = ref()
watch(
    () => studentistStore.studentList,
    () => people.value = studentistStore.studentList,
    { deep: true }
)
const props = defineProps({
    tableData: Array
})
const people = ref(studentistStore.studentList);
const form = ref({
    studentID: '',
    name: '',
    editIndex: 0
});
const addForm = ref({
    name: '',
    studentID: ''
});
const multipleTableRef = ref()
const dialogFormVisible = ref(false);
const addPerson = async () => {
        const data = {
            name: addForm.value.name,
            studentID: addForm.value.studentID,
            password: '1234',
            classID:classIDstore.classID
        };
        people.value.push(data)
        addForm.value = {}
        await addSingleStudent(data)
};
//保存多选行的信息
const selectionRow = ref([])
const handleSelectionChange = (section) => {
    selectionRow.value = section
    console.log(selectionRow.value, 'selectionRow')
}
//批量删除
const deleteBatchTeacher = async () => {
        const data = []
        selectionRow.value.map((item, index) => {
            data.push(item.studentID)
            people.value.map((list, idx) => {
                if (item.studentID === list.studentID)
                    people.value.splice(idx, 1)
            })
        })
        await deleteBatchStudents(data) 
}
const editPerson = async (row) => {
    // 处理选中行数据
    form.value.name = row.name;
    form.value.studentID = row.studentID;
    dialogFormVisible.value = true;
}
//删除单个學生
const deleteSingleStudentFun = async (row) => {
        const index = people.value.findIndex(item => item.studentID === row.studentID);
        people.value.splice(index, 1)
        const data = {
            classID: store.detailClass.classID,
            studentID: row.studentID
        }
        await deleteSingleStudentInClass(data)
};
//保存编辑内容
const saveEdit = async () => {
    const data = {
        name: form.value.name,
        password: "123456",//设为初始值
        studentID: form.value.studentID
    }
    await editorStudentInfo(data)
    const index = people.value.findIndex((item) => item.studentID === form.value.studentID)
    people.value[index].name = form.value.name
}
const searchQuery = ref('');

const search = async () => {
    const generateKeyData = () => {
        const part = searchQuery.value.split("&")
        const firstWord = searchQuery.value.charAt(0)
        if (firstWord === '&') {
            const data = {
                name: part[1],
                pageNum: 1,
                pageSize: 10
            }
            return data
        }
        if (part.length == 2) {
            const data = {
                name: part[1],
                studentID: part[0],
                pageNum: 1,
                pageSize: 10
            }
            return data
        }
        const data = {
            studentID: part[0],
            pageNum: 1,
            pageSize: 10
        }
        return data
    }
    const result = generateKeyData()
    const res = await selectSudentInfoService(result)
    people.value = res.data
};

const handleCloseDialog = (done) => {
    form.value.studentID = '';
    form.value.teacherName = '';
    done();
};

// 将响应式数据转换为可解构的对象
const { value: reactivePeople } = toRefs(people);
const downLoadStu = () => {
    const worksheet = XLSX.utils.json_to_sheet(people.value);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, 'students.xlsx');
}
const handleFileUpload = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        // 将数据存入ref
        people.value = jsonData.map((row, index) => {
            if (index === 0) return null; // 跳过表头行
            const [id, studentID, studentName] = row;
            return { id, studentID, studentName };
        }).filter(Boolean);
    };

    reader.readAsArrayBuffer(file);
}

</script>
  
<style>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.import_div {
    display: inline-block;
    margin-left: 28%;
}
</style>
   -->
  <!-- 引入 Element Plus 组件库 -->
<!-- <script>
export default {
    components: {
        ElNotification,
        ElDialog,
        ElForm,
        ElFormItem,
        ElInput,
        ElButton,
    },
};
</script>@/api/adminApi/allAdmin -->
    
    